﻿#ifndef ENCODER_H
#define ENCODER_H

#include <QString>
#include <QStringList>
#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>

void encode(const QString &input, const QString &output)
{
    if(!QFile::exists(input))
    {
        qDebug() << "error: file not exists";
        return;
    }

    QFile input_file(input);
    if(!input_file.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug() << "error: file cannot open";
        return;
    }

    QJsonDocument doc=QJsonDocument::fromJson(input_file.readAll());
    if(doc.isEmpty())
    {
        qDebug() << "error: format incorrect";
        return;
    }

    QFile output_file(output);
    if(output_file.open(QFile::WriteOnly))
    {
        output_file.write(doc.toBinaryData());
        output_file.close();
        qDebug() << "Finish";
    }
}

void decode(const QString &input, const QString &output)
{
    if(!QFile::exists(input))
    {
        qDebug() << "error: file not exists";
        return;
    }

    QFile input_file(input);
    if(!input_file.open(QFile::ReadOnly))
    {
        qDebug() << "error: file cannot open";
        return;
    }

    //二进制读
    QJsonDocument doc=QJsonDocument::fromBinaryData(input_file.readAll());
    if(doc.isEmpty())
    {
        qDebug() << "error: format incorrect";
        return;
    }

    QFile output_file(output);
    if(output_file.open(QFile::WriteOnly | QFile::Text))
    {
        output_file.write(doc.toJson());
        output_file.close();
        qDebug() << "Finish";
    }
}

#endif // ENCODER_H
